import pygame  # 导入pygame库
import random  # 导入random库
import sys  # 导入sys库
import math  # 导入math库
from enum import Enum  # 导入Enum类
from typing import Optional  # 顶部加类型注解
from 关卡 import guanqia  # 导入关卡系统
from 模型 import model  # 导入模型系统

# 初始化pygame
pygame.init()  # 初始化pygame

# 游戏窗口设置 - 修改为64x64总地图，24x24可视区域，36像素格子
TOTAL_MAP_SIZE = 64  # 总地图大小64x64
VISIBLE_MAP_SIZE = 24  # 可视区域大小24x24
CELL_SIZE = 36  # 每个格子的像素大小36
GAME_WIDTH = VISIBLE_MAP_SIZE * CELL_SIZE  # 游戏区域宽度 = 24 * 36 = 864
PANEL_WIDTH = 500  # 信息面板宽度增加到500
HEIGHT = VISIBLE_MAP_SIZE * CELL_SIZE  # 游戏区域高度 = 24 * 36 = 864
WIDTH = GAME_WIDTH + PANEL_WIDTH  # 总宽度 = 864 + 500 = 1364
screen = pygame.display.set_mode((WIDTH, HEIGHT))  # 创建窗口
pygame.display.set_caption("坦克大战 v14.0 - 64x64地图36像素版")  # 更新窗口标题
clock = pygame.time.Clock()  # 创建时钟对象
FPS = 60  # 帧率

# 颜色定义
WHITE = (255, 255, 255)  # 白色
BLACK = (0, 0, 0)  # 黑色
RED = (255, 0, 0)  # 红色
GREEN = (0, 255, 0)  # 绿色
BLUE = (0, 120, 255)  # 蓝色
YELLOW = (255, 255, 0)  # 黄色
DARK_GRAY = (50, 50, 50)  # 深灰色
LIGHT_BLUE = (100, 150, 255)  # 浅蓝色
PURPLE = (180, 0, 180)  # 紫色
LIGHT_YELLOW = (255, 255, 150)  # 浅黄色
WALL_COLOR = (120, 90, 60)  # 墙体颜色

# ======== 墙体形状枚举 ========
class WallShape(Enum):  # 墙体形状枚举类
    HORIZONTAL = 1  # 横向
    VERTICAL = 2  # 纵向
    L_SHAPE = 3  # L形
    T_SHAPE = 4  # T形
    CROSS = 5  # 十字形
    RANDOM = 6  # 随机

# ======== 游戏状态管理类 ========
class GameState:  # 游戏状态类
    """管理游戏状态，让坦克可以访问必要的游戏元素"""
    def __init__(self):  # 构造函数
        self.walls = []  # 墙体列表
        self.enemies = []  # 敌人列表
        self.player: Optional['Tank'] = None  # 玩家坦克，主循环中赋值
        self.level = 1  # 当前关卡
        self.camera_x = 0  # 摄像机X偏移量
        self.camera_y = 0  # 摄像机Y偏移量


# ======== 中文显示解决方案 ========
def get_font(size):  # 获取字体
    font_list = ['SimHei', 'Microsoft YaHei', 'Arial Unicode MS', 'sans-serif']  # 字体列表
    for font_name in font_list:  # 遍历字体
        try:
            return pygame.font.SysFont(font_name, size)  # 返回字体
        except:
            continue  # 出错则跳过
    return pygame.font.Font(None, size)  # 默认字体


# ======== 游戏界面功能 ========
def draw_health_bar(surface, x, y, health, max_health):
    bar_width = 300  # 调整血量条宽度以适应更大的面板
    bar_height = 40  # 调整血量条高度
    fill_width = int(bar_width * (health / max_health))
    outline_rect = pygame.Rect(x, y, bar_width, bar_height)
    fill_rect = pygame.Rect(x, y, fill_width, bar_height)
    pygame.draw.rect(surface, RED, outline_rect)
    pygame.draw.rect(surface, GREEN, fill_rect)
    pygame.draw.rect(surface, WHITE, outline_rect, 2)

    health_text = get_font(28).render(f"{health}/{max_health}", True, WHITE)
    surface.blit(health_text, (x + bar_width + 15, y))

def draw_info_panel(score, enemies_remaining, player_health, player_max_health, level, total_score):
    """绘制右侧信息面板"""
    # 面板背景
    pygame.draw.rect(screen, DARK_GRAY, (GAME_WIDTH, 0, PANEL_WIDTH, HEIGHT))
    pygame.draw.line(screen, LIGHT_BLUE, (GAME_WIDTH, 0), (GAME_WIDTH, HEIGHT), 3)

    # 字体设置 - 调整字体大小以适应更大的面板
    title_font = get_font(42)
    header_font = get_font(32)
    text_font = get_font(26)

    # 标题
    title = title_font.render("游戏信息", True, LIGHT_BLUE)
    screen.blit(title, (GAME_WIDTH + PANEL_WIDTH//2 - title.get_width()//2, 30))

    # 关卡信息
    max_level = guanqia.get_total_levels()
    level_text = header_font.render(f"当前关卡: {level}/{max_level}", True, PURPLE)
    screen.blit(level_text, (GAME_WIDTH + 20, 100))

    # 地图信息
    map_text = header_font.render(f"地图大小: 64x64", True, LIGHT_BLUE)
    screen.blit(map_text, (GAME_WIDTH + 20, 140))

    # 分数信息
    score_text = header_font.render(f"本关分数: {score}", True, YELLOW)
    screen.blit(score_text, (GAME_WIDTH + 20, 180))

    # 总分信息
    total_score_text = header_font.render(f"累计分数: {total_score}", True, YELLOW)
    screen.blit(total_score_text, (GAME_WIDTH + 20, 220))

    # 敌人信息
    enemies_text = header_font.render(f"剩余敌人: {enemies_remaining}", True, RED)
    screen.blit(enemies_text, (GAME_WIDTH + 20, 260))

    # 血量信息
    health_header = header_font.render("玩家血量:", True, GREEN)
    screen.blit(health_header, (GAME_WIDTH + 20, 300))
    draw_health_bar(screen, GAME_WIDTH + 20, 340, player_health, player_max_health)

    # 道具说明
    item_header = header_font.render("道具说明:", True, RED)
    screen.blit(item_header, (GAME_WIDTH + 20, 400))

    items = ["爱心: 恢复一格血量", "护盾: 免疫5s伤害"]

    for i, item in enumerate(items):
        item_text = text_font.render(item, True, WHITE)
        screen.blit(item_text, (GAME_WIDTH + 40, 440 + i * 45))

    # 墙体说明
    wall_header = header_font.render("墙体说明:", True, LIGHT_BLUE)
    screen.blit(wall_header, (GAME_WIDTH + 20, 530))

    walls = ["石墙: 无法击破", "木箱: 3次攻击击破，可能掉落道具", "草丛: 进入隐身状态"]

    for i, wall in enumerate(walls):
        wall_text = text_font.render(wall, True, WHITE)
        screen.blit(wall_text, (GAME_WIDTH + 40, 570 + i * 35))

    # 操作说明
    controls_header = header_font.render("操作说明:", True, LIGHT_BLUE)
    screen.blit(controls_header, (GAME_WIDTH + 20, 680))

    controls = [
        "方向键 ↑ : 向上移动",
        "方向键 ↓ : 向下移动",
        "方向键 ← : 向左移动",
        "方向键 → : 向右移动",
        "空格键    : 发射炮弹",
        "R  键     : 开始下一关"
    ]

    # 绘制操作说明
    for i, control in enumerate(controls):
        control_text = text_font.render(control, True, WHITE)
        screen.blit(control_text, (GAME_WIDTH + 40, 720 + i * 40))

def generate_walls_from_level_data(level_data):
    """根据关卡数据生成64x64墙体"""
    walls = []
    map_data = level_data.map_data
    
    for row_idx, row in enumerate(map_data):
        for col_idx, cell in enumerate(row):
            if cell in [0, 1, 2]:  # 0=石墙, 1=木箱, 2=草丛
                x = col_idx * CELL_SIZE
                y = row_idx * CELL_SIZE
                wall = model.Wall(x, y, cell, CELL_SIZE)  # 传入墙体类型和CELL_SIZE
                walls.append(wall)
    
    return walls

def generate_walls(level):
    """根据关卡生成墙体（兼容旧接口）"""
    level_data = guanqia.get_level_data(level)
    return generate_walls_from_level_data(level_data)

# ======== 游戏核心逻辑 ========
def reset_game(game_state):
    """根据地图数据生成玩家坦克"""
    level_data = guanqia.get_level_data(game_state.level)
    map_data = level_data.map_data
    
    # 在地图中查找玩家标记（数字4或5）
    for row_idx, row in enumerate(map_data):
        for col_idx, cell in enumerate(row):
            if cell in [4, 5]:  # 4=玩家坦克1（蓝色）, 5=玩家坦克2（黄色）
                x = col_idx * CELL_SIZE
                y = row_idx * CELL_SIZE
                color = BLUE if cell == 4 else YELLOW
                player = model.Tank(x, y, color, True, game_state)
                return player
    
    # 如果地图中没有玩家标记，使用默认位置
    x = TOTAL_MAP_SIZE * CELL_SIZE // 2 - 18
    y = TOTAL_MAP_SIZE * CELL_SIZE // 2 - 18
    return model.Tank(x, y, BLUE, True, game_state)

def generate_enemies(level, game_state):
    """根据地图数据生成敌人坦克"""
    level_data = guanqia.get_level_data(level)
    map_data = level_data.map_data
    enemies = []
    
    # 在地图中查找敌人标记（数字6）
    for row_idx, row in enumerate(map_data):
        for col_idx, cell in enumerate(row):
            if cell == 6:  # 6=敌人坦克（红色）
                x = col_idx * CELL_SIZE
                y = row_idx * CELL_SIZE
                enemy = model.Tank(x, y, RED, False, game_state)
                enemies.append(enemy)
    
    # 如果地图中没有敌人标记，使用默认数量生成
    if not enemies:
        enemy_count = level_data.enemy_count
        for _ in range(enemy_count):
            tries = 0
            while tries < 100:
                x = random.randint(50, TOTAL_MAP_SIZE * CELL_SIZE - 86)
                y = random.randint(50, TOTAL_MAP_SIZE * CELL_SIZE - 86)
                enemy_rect = pygame.Rect(x, y, 36, 36)
                
                # 检查与墙体是否重叠
                collision = False
                for wall in game_state.walls:
                    if wall.alive and wall.rect.colliderect(enemy_rect):
                        collision = True
                        break
                        
                if not collision:
                    enemies.append(model.Tank(x, y, RED, False, game_state))
                    break
                tries += 1
            else:
                # 实在找不到就放左上角
                enemies.append(model.Tank(CELL_SIZE, CELL_SIZE, RED, False, game_state))
    
    return enemies

# ======== 摄像机系统 ========
def update_camera(game_state):
    """更新摄像机位置，让摄像机跟随玩家"""
    if game_state.player and game_state.player.live:
        # 计算玩家在屏幕中心的位置
        target_camera_x = game_state.player.x - GAME_WIDTH // 2 + game_state.player.size // 2
        target_camera_y = game_state.player.y - HEIGHT // 2 + game_state.player.size // 2
        
        # 限制摄像机不超出地图边界
        max_camera_x = TOTAL_MAP_SIZE * CELL_SIZE - GAME_WIDTH
        max_camera_y = TOTAL_MAP_SIZE * CELL_SIZE - HEIGHT
        
        game_state.camera_x = max(0, min(max_camera_x, target_camera_x))
        game_state.camera_y = max(0, min(max_camera_y, target_camera_y))

def world_to_screen(world_x, world_y, camera_x, camera_y):
    """将世界坐标转换为屏幕坐标"""
    screen_x = world_x - camera_x
    screen_y = world_y - camera_y
    return screen_x, screen_y

def screen_to_world(screen_x, screen_y, camera_x, camera_y):
    """将屏幕坐标转换为世界坐标"""
    world_x = screen_x + camera_x
    world_y = screen_y + camera_y
    return world_x, world_y

def main_game_loop():
    """游戏主循环"""
    game_state = GameState()  # 先创建状态
    level = 1
    game_state.level = level  # 设置游戏状态的关卡
    total_score = 0
    level_data = guanqia.get_level_data(level)
    game_state.walls = generate_walls_from_level_data(level_data)  # 先生成墙体
    player = reset_game(game_state)  # 再生成玩家
    game_state.player = player
    game_state.enemies = generate_enemies(level, game_state)  # 再生成敌人
    score = 0
    game_over = False
    victory = False
    level_complete = False
    current_item = None
    last_item_time = pygame.time.get_ticks()
    item_spawn_delay = level_data.item_settings['item_spawn_delay']
    heal_effects = []

    while True:
        current_time = pygame.time.get_ticks()

        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and not game_over and player.live and not level_complete:
                    player.fire()

                # R键进入下一关功能
                if event.key == pygame.K_r:
                    # 关卡完成时进入下一关
                    if level_complete:
                        max_level = guanqia.get_total_levels()
                        if level < max_level:
                            level += 1
                            game_state.level = level  # 更新游戏状态的关卡
                            total_score += score
                            level_data = guanqia.get_level_data(level)
                            game_state.walls = generate_walls_from_level_data(level_data)
                            player = reset_game(game_state)
                            game_state.player = player
                            game_state.enemies = generate_enemies(level, game_state)
                            score = 0
                            level_complete = False
                            victory = False
                            current_item = None
                            last_item_time = current_time
                            item_spawn_delay = level_data.item_settings['item_spawn_delay']
                        else:
                            # 通关后重新开始游戏
                            level = 1
                            game_state.level = level  # 更新游戏状态的关卡
                            total_score = 0
                            level_data = guanqia.get_level_data(level)
                            game_state.walls = generate_walls_from_level_data(level_data)
                            player = reset_game(game_state)
                            game_state.player = player
                            game_state.enemies = generate_enemies(level, game_state)
                            score = 0
                            game_over = False
                            victory = False
                            level_complete = False
                            current_item = None
                            last_item_time = current_time
                            item_spawn_delay = level_data.item_settings['item_spawn_delay']
                    # 游戏失败时重新开始
                    elif game_over:
                        level = 1
                        game_state.level = level  # 更新游戏状态的关卡
                        total_score = 0
                        level_data = guanqia.get_level_data(level)
                        game_state.walls = generate_walls_from_level_data(level_data)
                        player = reset_game(game_state)
                        game_state.player = player
                        game_state.enemies = generate_enemies(level, game_state)
                        score = 0
                        game_over = False
                        level_complete = False
                        current_item = None
                        last_item_time = current_time
                        item_spawn_delay = level_data.item_settings['item_spawn_delay']

        # 道具生成逻辑
        if not current_item and not game_over and not level_complete:
            if current_time - last_item_time > item_spawn_delay:
                # 根据关卡设置生成道具
                level_data = guanqia.get_level_data(level)
                health_rate = level_data.item_settings['health_spawn_rate']
                shield_rate = level_data.item_settings['shield_spawn_rate']
                
                # 根据概率生成道具
                rand = random.random()
                if rand < health_rate:
                    item_type = 'health'
                elif rand < health_rate + shield_rate:
                    item_type = 'shield'
                else:
                    item_type = random.choice(['health', 'shield'])  # 默认选择
                
                # 在随机位置生成道具
                tries = 0
                while tries < 100:
                    x = random.randint(50, TOTAL_MAP_SIZE * CELL_SIZE - 50)
                    y = random.randint(50, TOTAL_MAP_SIZE * CELL_SIZE - 50)
                    item_rect = pygame.Rect(x - 18, y - 18, 36, 36)  # 道具半径18
                    collision = False
                    for wall in game_state.walls:
                        if wall.alive and wall.rect.colliderect(item_rect):
                            collision = True
                            break
                    if not collision:
                        current_item = model.Item(item_type, x, y)
                        break
                    tries += 1
                # 实在找不到就放左上角
                if tries >= 100:
                    current_item = model.Item(item_type, CELL_SIZE, CELL_SIZE)
                last_item_time = current_time
        
        # 道具拾取检测
        if current_item and current_item.active and not game_over and not level_complete:
            if current_item.check_collision(player):
                if current_item.type == 'health':
                    # 尝试回血并显示特效
                    if player.add_health():
                        heal_effects.append({
                            'x': player.x + player.size // 2,
                            'y': player.y + player.size // 2,
                            'start_time': current_time,
                            'duration': 1000  # 1秒
                        })
                elif current_item.type == 'shield':
                    player.activate_shield(5000)  # 5秒护盾
                
                # 道具被拾取后消失
                current_item.active = False
                current_item = None
                last_item_time = current_time
        
        # 更新回血特效
        for effect in heal_effects[:]:
            elapsed = current_time - effect['start_time']
            if elapsed > effect['duration']:
                heal_effects.remove(effect)
            else:
                # 更新位置（向上移动）
                effect['y'] -= 1
        
        if not game_over and not level_complete:
            # 获取按键状态
            keys = pygame.key.get_pressed()
            player.move(keys, TOTAL_MAP_SIZE, CELL_SIZE)
            
            # 更新摄像机位置
            update_camera(game_state)
            
            # 敌人随机开火
            for enemy in game_state.enemies:
                if enemy.live and random.randint(0, 100) < 1:
                    enemy.fire()
                enemy.move(None, TOTAL_MAP_SIZE, CELL_SIZE)
        
        # 清屏
        screen.fill(BLACK)
        
        # 游戏区域背景
        game_surface = pygame.Surface((GAME_WIDTH, HEIGHT))
        game_surface.fill((30, 30, 30))
        screen.blit(game_surface, (0, 0))
        
        # 绘制墙体 - 只绘制在可视区域内的墙体
        for wall in game_state.walls:
            wall.draw(game_surface, game_state.camera_x, game_state.camera_y)
        
        # 更新和绘制子弹
        if not game_over and not level_complete:
            # 玩家子弹
            for bullet in player.bullets[:]:
                # 更新消失动画
                if not bullet.update_fade():
                    player.bullets.remove(bullet)
                    continue
                
                # 检测子弹与墙体碰撞（在移动之前检测）
                bullet_rect = bullet.get_rect()
                bullet_hit_wall = False
                bullet_should_remove = False
                
                for wall in game_state.walls[:]:
                    if wall.alive and wall.wall_type != 2 and wall.check_collision(bullet_rect):  # 草丛不阻挡子弹
                        wall_hit = wall.hit()  # 墙体被击中，可能被摧毁
                        bullet_hit_wall = True
                        # 如果是木箱被摧毁，尝试生成道具
                        if wall.wall_type == 1 and not wall.alive:
                            generated_item = wall.generate_item_on_destroy()
                            if generated_item:
                                current_item = generated_item
                                last_item_time = current_time
                        # 只有当墙体被摧毁时才移除子弹
                        if wall_hit:
                            bullet_should_remove = True
                        break
                
                # 如果子弹击中了墙体，立即移除子弹并跳过后续处理
                if bullet_hit_wall:
                    if bullet_should_remove:
                        player.bullets.remove(bullet)
                    else:
                        # 如果墙体没有被摧毁，也要移除子弹（避免重复击中）
                        player.bullets.remove(bullet)
                    continue
                
                # 子弹移动
                bullet.move()
                
                # 转换子弹坐标到屏幕坐标
                screen_x, screen_y = world_to_screen(bullet.x, bullet.y, game_state.camera_x, game_state.camera_y)
                # 只绘制在可视区域内的子弹
                if -bullet.size <= screen_x <= GAME_WIDTH and -bullet.size <= screen_y <= HEIGHT:
                    # 使用子弹自己的绘制方法（支持透明度）
                    bullet.draw(game_surface, game_state.camera_x, game_state.camera_y)
                
                # 检测玩家子弹击中敌人
                for enemy in game_state.enemies[:]:
                    if (enemy.live and
                        enemy.x < bullet.x < enemy.x + enemy.size and
                        enemy.y < bullet.y < enemy.y + enemy.size):
                        if enemy.hit():
                            score += 1000  # 每个敌人价值1000分
                        player.bullets.remove(bullet)
                        break
                
                # 移除出界子弹
                if bullet.is_out_of_bounds(TOTAL_MAP_SIZE, CELL_SIZE) and bullet in player.bullets:
                    player.bullets.remove(bullet)
            
            # 敌人子弹
            for enemy in game_state.enemies:
                for bullet in enemy.bullets[:]:
                    # 更新消失动画
                    if not bullet.update_fade():
                        enemy.bullets.remove(bullet)
                        continue
                    
                    # 检测子弹与墙体碰撞（在移动之前检测）
                    bullet_rect = bullet.get_rect()
                    bullet_hit_wall = False
                    bullet_should_remove = False
                    
                    for wall in game_state.walls[:]:
                        if wall.alive and wall.wall_type != 2 and wall.check_collision(bullet_rect):  # 草丛不阻挡子弹
                            wall_hit = wall.hit()  # 墙体被击中，可能被摧毁
                            bullet_hit_wall = True
                            # 如果是木箱被摧毁，尝试生成道具
                            if wall.wall_type == 1 and not wall.alive:
                                generated_item = wall.generate_item_on_destroy()
                                if generated_item:
                                    current_item = generated_item
                                    last_item_time = current_time
                            # 只有当墙体被摧毁时才移除子弹
                            if wall_hit:
                                bullet_should_remove = True
                            break
                    
                    # 如果子弹击中了墙体，立即移除子弹并跳过后续处理
                    if bullet_hit_wall:
                        if bullet_should_remove:
                            enemy.bullets.remove(bullet)
                        else:
                            # 如果墙体没有被摧毁，也要移除子弹（避免重复击中）
                            enemy.bullets.remove(bullet)
                        continue
                    
                    # 子弹移动
                    bullet.move()
                    
                    # 转换子弹坐标到屏幕坐标
                    screen_x, screen_y = world_to_screen(bullet.x, bullet.y, game_state.camera_x, game_state.camera_y)
                    # 只绘制在可视区域内的子弹
                    if -bullet.size <= screen_x <= GAME_WIDTH and -bullet.size <= screen_y <= HEIGHT:
                        # 使用子弹自己的绘制方法（支持透明度）
                        bullet.draw(game_surface, game_state.camera_x, game_state.camera_y)
                    
                    # 检测敌人子弹击中玩家
                    if (player.live and
                        player.x < bullet.x < player.x + player.size and
                        player.y < bullet.y < player.y + player.size):
                        player.hit()
                        enemy.bullets.remove(bullet)
                    
                    # 移除出界子弹
                    if bullet.is_out_of_bounds(TOTAL_MAP_SIZE, CELL_SIZE) and bullet in enemy.bullets:
                        enemy.bullets.remove(bullet)
        
        # 绘制坦克
        # 玩家坦克
        player.draw(game_surface, game_state.camera_x, game_state.camera_y)
        
        # 敌人坦克
        for enemy in game_state.enemies:
            enemy.draw(game_surface, game_state.camera_x, game_state.camera_y)
        
        # 绘制道具
        if current_item and current_item.active:
            screen_x, screen_y = world_to_screen(current_item.x, current_item.y, game_state.camera_x, game_state.camera_y)
            if -current_item.radius <= screen_x <= GAME_WIDTH and -current_item.radius <= screen_y <= HEIGHT:
                # 创建道具绘制函数
                def draw_item_on_surface(surface, item, x, y):
                    if not item.active:
                        return
                    
                    item.pulse_value = (item.pulse_value + item.pulse_speed) % (2 * math.pi)
                    pulse_size = item.radius + 3 * math.sin(item.pulse_value)
                    
                    if item.type == 'health':  # 爱心道具
                        points = []
                        for angle in range(0, 360, 10):
                            rad = math.radians(angle)
                            px = pulse_size * (math.sin(rad) ** 3)
                            py = pulse_size * (math.cos(rad) - math.cos(rad*2) - math.cos(rad*3) - math.cos(rad*4)) / 3.5
                            points.append((x + px, y - py))
                        pygame.draw.polygon(surface, RED, points)
                    elif item.type == 'shield':  # 护盾道具
                        pygame.draw.circle(surface, LIGHT_YELLOW, (x, y), int(pulse_size), 3)
                        pygame.draw.circle(surface, LIGHT_YELLOW, (x, y), int(pulse_size) - 8, 3)
                        pygame.draw.arc(surface, LIGHT_YELLOW, (x - pulse_size, y - pulse_size, pulse_size * 2, pulse_size * 2), math.pi/4, 3*math.pi/4, 3)
                
                draw_item_on_surface(game_surface, current_item, screen_x, screen_y)
            
        # 绘制回血特效
        for effect in heal_effects:
            elapsed = current_time - effect['start_time']
            alpha = 255 - int(255 * elapsed / effect['duration'])
            text = get_font(24).render("+1", True, (0, 255, 0, alpha))
            text_surface = pygame.Surface(text.get_size(), pygame.SRCALPHA)
            text_surface.blit(text, (0, 0))
            # 转换特效坐标到屏幕坐标
            screen_x, screen_y = world_to_screen(effect['x'], effect['y'], game_state.camera_x, game_state.camera_y)
            if -text.get_width() <= screen_x <= GAME_WIDTH and -text.get_height() <= screen_y <= HEIGHT:
                screen.blit(text_surface, (screen_x - text.get_width()//2, screen_y - text.get_height()//2))
        
        # 显示游戏区域
        screen.blit(game_surface, (0, 0))
        
        # 计算剩余敌人数量
        enemies_remaining = sum(1 for enemy in game_state.enemies if enemy.live)
        
        # 绘制右侧信息面板
        draw_info_panel(score, enemies_remaining, player.health, player.max_health, level, total_score)
        
        # 关卡完成检测
        if enemies_remaining == 0 and player.live and not level_complete:
            level_complete = True
            victory = True
        
        # 显示关卡完成提示
        if level_complete:
            # 通关提示
            max_level = guanqia.get_total_levels()
            if level < max_level:
                level_text = get_font(72).render(f"第{level}关完成!", True, GREEN)
                next_level_text = get_font(36).render("按 R 键进入下一关", True, YELLOW)
                screen.blit(level_text, (GAME_WIDTH//2 - 150, HEIGHT//2 - 72))
                screen.blit(next_level_text, (GAME_WIDTH//2 - 150, HEIGHT//2 + 20))
            else:
                win_text = get_font(72).render("恭喜通关!", True, PURPLE)
                restart_text = get_font(36).render("按 R 键重新开始游戏", True, YELLOW)
                screen.blit(win_text, (GAME_WIDTH//2 - 150, HEIGHT//2 - 72))
                screen.blit(restart_text, (GAME_WIDTH//2 - 150, HEIGHT//2 + 20))
        
        # 游戏结束检测
        if not player.live and not game_over:
            game_over = True
            text = get_font(72).render("游戏结束!", True, RED)
            restart_text = get_font(36).render("按 R 键重新开始游戏", True, WHITE)
            screen.blit(text, (GAME_WIDTH//2 - 150, HEIGHT//2 - 36))
            screen.blit(restart_text, (GAME_WIDTH//2 - 150, HEIGHT//2 + 50))
        
        pygame.display.flip()
        clock.tick(FPS)

if __name__ == "__main__":
    main_game_loop()